package describe

import (
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
)

/*
解包
*/
var (
	snapshot_len int32 = 1024
	promiscuous  bool  = false
	err          error
	timeout      time.Duration = 30 * time.Second
	handle       *pcap.Handle
)

func Explain(device string) {
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)

	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		describe(packet)
	}
}

func describe(packet gopacket.Packet) {
	ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
	if ethernetLayer != nil {
		ethernetPacket, _ := ethernetLayer.(*layers.Ethernet)
		fmt.Printf("网卡信息:{源mac:%s,目标mac:%s,类型:%s}\n", ethernetPacket.SrcMAC, ethernetPacket.DstMAC, ethernetPacket.EthernetType)
	}
	ipLayers := packet.Layer(layers.LayerTypeIPv4)
	if ipLayers != nil {
		ip, _ := ipLayers.(*layers.IPv4)
		fmt.Printf("协议:%s,从%s到%s\n", ip.Protocol, ip.SrcIP, ip.DstIP)
	}
	tcpLayers := packet.Layer(layers.LayerTypeTCP)
	if tcpLayers != nil {
		tcp, _ := tcpLayers.(*layers.TCP)
		fmt.Printf("Sequence is %d,从%d到%d\n", tcp.Seq, tcp.SrcPort, tcp.DstPort)
	}

	fmt.Print("all packet layers")
	for _, layer := range packet.Layers() {
		fmt.Print("-", layer.LayerType())
	}
	fmt.Println()

	applicationlayer := packet.ApplicationLayer()
	if applicationlayer != nil {
		fmt.Println(string(applicationlayer.Payload()))
		if strings.Contains(string(applicationlayer.Payload()), "HTTP") {
			fmt.Println("这是一个HTTP请求")
		}
	}
	if err := packet.ErrorLayer(); err != nil {
		fmt.Println("解包出错:", err)
	}

}
